package com.example.security.mapper;

import com.example.security.entity.SysPermission;
import org.apache.ibatis.annotations.*;

import java.util.List;
import java.util.Set;

@Mapper
public interface PermissionMapper {

    @Select("SELECT * FROM sys_permission")
    List<SysPermission> selectAll();

    @Select("SELECT * FROM sys_permission WHERE id = #{id}")
    SysPermission selectById(Long id);

    @Select("SELECT * FROM sys_permission WHERE enname = #{enname}")
    SysPermission selectByEnname(String enname);

    @Insert("INSERT INTO sys_permission(parent_id, name, enname, url, type, sort, icon, status, description) " +
            "VALUES(#{parentId}, #{name}, #{enname}, #{url}, #{type}, #{sort}, #{icon}, #{status}, #{description})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insert(SysPermission permission);

    @Update("UPDATE sys_permission SET parent_id=#{parentId}, name=#{name}, enname=#{enname}, " +
            "url=#{url}, type=#{type}, sort=#{sort}, icon=#{icon}, status=#{status}, " +
            "description=#{description} WHERE id=#{id}")
    void update(SysPermission permission);

    @Delete("DELETE FROM sys_permission WHERE id = #{id}")
    void delete(Long id);

    @Select("SELECT DISTINCT p.enname FROM sys_permission p " +
            "LEFT JOIN sys_role_permission rp ON p.id = rp.permission_id " +
            "LEFT JOIN sys_user_role ur ON rp.role_id = ur.role_id " +
            "WHERE ur.user_id = #{userId}")
    Set<String> selectPermissionsByUserId(Long userId);

    @Select("SELECT COUNT(*) FROM sys_permission WHERE parent_id = #{parentId}")
    int countByParentId(Long parentId);

    void deleteById(Long id);
}